package com.ganzalang.gmall.gmallfreemarker.controller;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.Claim;
import com.ganzalang.gmall.gmallfreemarker.api.dto.UserDTO;
import com.ganzalang.gmall.gmallfreemarker.api.req.UserLoginReq;
import com.ganzalang.gmall.gmallfreemarker.common.api.BaseResult;
import com.ganzalang.gmall.gmallfreemarker.demo.db.UserDb;
import com.ganzalang.gmall.gmallfreemarker.demo.entity.UserDemoEntity;
import com.ganzalang.gmall.gmallfreemarker.intercepter.AuthInterceptor;
import com.ganzalang.gmall.gmallfreemarker.util.JwtUtil;
import com.ganzalang.gmall.gmallfreemarker.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Map;

@Controller
@Slf4j
public class AuthController {

    @Resource
    private JwtUtil jwtUtil;

    @GetMapping("/login")
    public String login() {
        return "login/login-index";
    }

    @PostMapping("/login")
    @ResponseBody
    public BaseResult<String> handleLogin(@RequestBody @Valid UserLoginReq req, HttpServletRequest request) throws IOException {
        UserDemoEntity userDemo = UserDb.listUsers().get(0);
        if (userDemo.getPassword().equals(req.getPassword()) && userDemo.getUsername().equals(req.getUsername())) {
            UserDTO userDTO = new UserDTO();
            userDTO.setId(userDemo.getId());
            userDTO.setUsername(userDemo.getUsername());
            userDTO.setPassword(userDemo.getPassword());
            String token = jwtUtil.createJwt(userDTO, userDTO.getId().toString());
            log.info("handle login, req:{}, token:{}", JSON.toJSONString(req), token);
            return BaseResult.success(token);
        } else {
            return BaseResult.success("密码错误", null);
        }

    }
}
